import {
  Controller,
  Get,
  Post,
  Body,
  Query,
  Res,
  HttpException,
} from '@nestjs/common';
import { WechatService } from './wechat.service';
import { Response } from 'express';
import { WechatFan } from './mongo/wechat-fan.entity';
import { CallbackParams, BindPhoneDto } from './wechat.types';
@Controller('wechat')
export class WechatController {
  constructor(private readonly wechatService: WechatService) {}

  @Get('callback')
  verifyServer(@Query() params: CallbackParams) {
    console.log('verifyServer');
    return this.wechatService.verifyWechatSignature(params);
  }

  @Post('callback')
  async receiveMessage(
    @Query() params: CallbackParams, // 这里也需要改为CallbackParams类型
    @Body() rawBody: Buffer,
    @Res() res: Response,
  ) {
    // 第一步：验证消息签名（确保来自微信服务器）
    console.log('receiveMessage');
    const isVerified = this.wechatService.verifyWechatSignature(params);
    console.log(isVerified, 23964206);
    if (!isVerified) {
      throw new HttpException('非法请求', 403);
    }

    // 第二步：解析XML格式的消息
    const xml = rawBody.toString();
    console.log(xml, 892364918);
    let message: Record<string, any> | undefined;
    try {
      message = await this.wechatService.parseXmlToJson(xml);
      console.log('收到用户消息：', message);
    } catch (error) {
      console.log(error, 'parseXmlToJson失败');
      throw new HttpException('消息解析失败', 500);
    }

    if (!message) {
      throw new HttpException('未解析到有效消息', 400);
    }

    // 第三步：处理消息（示例：被动回复文本消息）
    let replyXml: string;
    try {
      replyXml = this.wechatService.generateReplyXml(
        message,
        `已收到：${message.Content || ''}`,
      );
    } catch (error) {
      console.log(error, 'generateReplyXml失败');
      throw new HttpException('回复消息生成失败', 500);
    }

    // 第四步：返回回复（5秒内，XML格式）
    res.type('application/xml');
    res.send(replyXml);
  }

  @Get('binding-phone')
  async checkBinding(@Query('code') code: string): Promise<WechatFan | null> {
    if (!code) {
      throw new HttpException('缺少code参数', 400);
    }
    return this.wechatService.checkUserPhone(code);
  }

  @Post('bind-phone')
  async bindPhone(@Body() body: BindPhoneDto) {
    const { openid, phone, role } = body;
    if (!openid || !phone || !role) {
      throw new HttpException('缺少必要参数', 400);
    }
    return this.wechatService.bindUserPhone(phone, role, openid);
  }
}
